上一篇中提到了React與Redux的結合並且設計了Component的階層,本篇將照著設計好的Component進行實作。
建立產生Action的Function,包含 :
let nextTodoId = 0;
//新增Todo的Action
export const addTodo = (text) => {
return{
type : "ADD_TODO",
id : nextTodoId++,
text
}
};
//設定篩選Filter的Aciton
export const setVisibilityFilter = (filter) => {
return {
type: 'SET_VISIBILITY_FILTER',
filter
}
};
//指定id Todo 的Action
export const toggleTodo = (id) => {
return {
type: 'TOGGLE_TODO',
id
}
};
建立處理Action的Reducer,包含 :
處理Todos的Reducer
處理visibilityFilter的Reducer
import { combineReducers } from 'redux'
//將Reducer拆分
const todo = (state = {}, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
}
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state
}
return Object.assign({}, state, {
completed: !state.completed
})
default:
return state
}
}
const todos = (state = [], action) => {
switch (action.type) {
//呼叫todo function,新增新的todo到原本的Todos Array中
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
]
//改變指定todo狀態
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
)
default:
return state
}
}
const visibilityFilter = (state = 'SHOW_ALL', action) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
//透過Redux的utility 將兩個Reducer function結合為一個可以傳遞給createStore的單一reducers function
export const todoApp = combineReducers({
todos,
visibilityFilter
})
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { createStore } from "redux";
import { Provider } from "react-redux";
import todoApp from "./Store/Reducers"
let store = createStore(todoApp);
//透過getState觀察目前state狀態
console.log(store.getState())
ReactDOM.render(
<Provider store = {store}>
<App />
</Provider>,
document.getElementById("root")
);
參考資料 :
從Redux 的作者學習它